package cn.study.zgm.nettyall.selector.nio;

import cn.study.zgm.nettyall.channel.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * packageName cn.study.zgm.nettyall.selector.bio
 *
 * @author 你的名字
 * @version JDK 8
 * @className NoBlockingServer (此处以class为例)
 * @date 2025/2/25
 * @description TODO
 */
@Slf4j
public class NoBlockingServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        ByteBuffer buffer = ByteBuffer.allocate(32);
        // 1.创建一个客户端
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress("127.0.0.1", 8081));
        ssc.configureBlocking(false);// 设置为非阻塞模式

        List<SocketChannel> channelList = new ArrayList<>();
        while (true){
            Thread.sleep(1000);
            SocketChannel channel = ssc.accept();
            if (channel !=null){
                log.error("服务器开始连接中[{}]",channel);
                channel.configureBlocking(false); // 设置channel为非阻塞
                channelList.add(channel);
                log.error("服务器已经连接到[{}]",channel);
            }

            for (SocketChannel socketChannel : channelList) {
                final int read = socketChannel.read(buffer);
                if (read <=0){
                    continue;
                }
                log.error("服务器接收到[{}]发送的消息",socketChannel);
                buffer.flip();
                ByteBufferUtil.debugRead(buffer);
                buffer.clear();
                log.error("服务器读取[{}]消息结束>>>>",socketChannel);
            }
        }
    }
}
